import React, { useContext } from 'react';
import cornerstoneTools from 'cs-cornerstone-tools';

let SynchronizerContext = React.createContext({});

export const useSynchronizerContext = () => useContext(SynchronizerContext);

export const SynchronizerProvider = ({ children }) => {
  const synchronizers = new Map();

  let synchronizer = new cornerstoneTools.Synchronizer(
    'cornerstonenewimage',
    cornerstoneTools.updateImageSynchronizer
  );
  cornerstoneTools.addTool(cornerstoneTools.ReferenceLinesTool);
  cornerstoneTools.setToolEnabled('ReferenceLines', {
    synchronizationContext: synchronizer,
  });
  synchronizers.set('refLineSync', synchronizer);

  synchronizer = new cornerstoneTools.Synchronizer(
    'cornerstonenewimage',
    cornerstoneTools.stackImagePositionSynchronizer
  )
  synchronizers.set('positionSync', synchronizer);

  synchronizer = new cornerstoneTools.Synchronizer(
    'cornerstonenewimage',
    cornerstoneTools.stackImageIndexSynchronizer
  )
  synchronizers.set('indexSync', synchronizer);

  return (
    <SynchronizerContext.Provider value={{ synchronizers }}>
      {children}
    </SynchronizerContext.Provider>
  );
};

export const withSynchronizerContext = Component => {
  return function WrappedComponent(props) {
    const { synchronizers } = useSynchronizerContext();
    return (
      <Component {...props} synchronizers={synchronizers} />
    );
  };
};

export default SynchronizerContext;
